package com.szml.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JWTUtils {
    private static final String SIGNATURE = "!#SZe$%5Rwer231#$fsreg455"; //签名
    /**
     * 生成token header.payload.signature
     */
    public static String getToken(Map<String,String> map){
        Calendar instance = Calendar.getInstance();  //日历
        instance.add(Calendar.DATE, 7);//默认7天过期

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        //payload
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        String token = builder.withExpiresAt(instance.getTime()) //指定过期时间
        .sign(Algorithm.HMAC256(SIGNATURE));  //signature
        return token;

//        String token = JWT.create()
//                .withClaim("userId", 12)
//                .withClaim("username", "lili")
//                .withExpiresAt(instance.getTime())
//                .sign(Algorithm.HMAC256(JWTUtil.SIGNATURE));
    }

    /**
     * 验证token、也可通过这个DecodedJWT类型的返回值来获取里面的信息
     */
    public static DecodedJWT verify(String token){
        //verify 验证
        //如果签名错误或过期等任何问题，就会抛出异常
        return JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);

        //创建验证对象
        //JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("!#SZe$%5")).build();
        //解码对象
        //DecodedJWT verify = jwtVerifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3NDk4NzIzMTAsInVzZXJJZCI6MjEsInVzZXJuYW1lIjoibGlsaSJ9.l9NPHQ0hSjNNS4yhHIjsX-AnWdR6IyswHoSBlFdzQpI");
        //System.out.println(verify.getClaim("userId").asInt());  //21
        //System.out.println(verify.getClaim("username").asString());  //lili

    }

//    /**
//     * 获取token信息的方法
//     */
//    public static DecodedJWT getTokenInfo(String token){
//        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);//algorithm 算法
//        return verify;
//    }

}
